<?php 
class ControllerSurveyResult extends Controller { 
	private $error = array();
	
	public function index() {		
		$this->load->language('survey/result');

		$this->document->setTitle($this->language->get('heading_title'));
		
		$this->load->model('survey/survey');
		$this->load->model('survey/result');
				
		if ($this->request->server['REQUEST_METHOD'] == 'POST' && $this->validate()) {
			
			$result = array();
			$user_email = $this->request->post['email'];
			
			$all_surveys = $this->request->post['survey_ides'];
			
			foreach($all_surveys as $each_survey) {
				$survey_info = $this->model_survey_survey->getSurvey($each_survey); 
				$result[$each_survey]['name'] = $survey_info['title'];
				$result[$each_survey]['output'] = $this->process($user_email, $each_survey);
			}						
//			print_r($result);
			
			$this->data['text_user'] = $user_email;
			
			$this->data['processed'] = $result;
		} else {
			$this->data['processed'] = array();
		}

		

		$this->data['heading_title'] = $this->language->get('heading_title');
		
		$this->data['text_select_all'] = $this->language->get('text_select_all');
		$this->data['text_unselect_all'] = $this->language->get('text_unselect_all');
		
		$this->data['entry_surveys'] = $this->language->get('entry_surveys');
		$this->data['entry_email'] = $this->language->get('entry_email');
		 
		$this->data['button_submit'] = $this->language->get('button_submit');
		$this->data['button_back'] = $this->language->get('button_back');
		
		$this->data['tab_general'] = $this->language->get('tab_general');
		
 		if (isset($this->error['warning'])) {
			$this->data['error_warning'] = $this->error['warning'];
		} else {
			$this->data['error_warning'] = '';
		}
		
		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];
		
			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}
		
		if (isset($this->error['email'])) {
			$this->data['error_email'] = $this->error['email'];
		} else {
			$this->data['error_email'] = '';
		}
		
		if (isset($this->error['survey_ides'])) {
			$this->data['error_survey_ides'] = $this->error['survey_ides'];
		} else {
			$this->data['error_survey_ides'] = '';
		}
		
  		$this->data['breadcrumbs'] = array();

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),     		
      		'separator' => false
   		);

   		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('heading_title'),
			'href'      => $this->url->link('survey/result', 'token=' . $this->session->data['token'], 'SSL'),
      		'separator' => ' :: '
   		);
		
		$this->data['action'] = $this->url->link('survey/result', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['back'] = $this->url->link('survey/result', 'token=' . $this->session->data['token'], 'SSL');

		$this->load->model('survey/survey');
		
		
		if (isset($this->request->post['email'])) {
      		$this->data['email'] = $this->request->post['email'];
    	} else {
      		$this->data['email'] = '';
    	}
    	
    	if (isset($this->request->post['survey_ides'])) {
      		$this->data['survey_ides'] = $this->request->post['survey_ides'];
    	} else {
      		$this->data['survey_ides'] = array(11,12,13,14,15);
    	}
		
		$data = array (
			'filter_status' => 1,
		);
		$this->data['surveys'] = $this->model_survey_survey->getSurveys($data);

		$this->template = 'survey/result.tpl';
		
		$this->children = array(
			'common/header',
			'common/footer',
		);
				
		$this->response->setOutput($this->render());
	}
	
	public function process($email, $survey_id) {
		$result = array();
		
		$this->data['surveys'] = array();

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			$sort = 'i.sort_order';
		}
		
		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}
		
		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$data = array(
			'filter_survey_id' => $survey_id			
		);
		
		$this->load->model('survey/question');
		$this->load->model('survey/answer');

		$data = array(
			'filter_email_exact' => $email,
			'start' => 0,
			'limit' => 1, 
		);
		
		$results = $this->model_survey_answer->getAnswers($data);
		
//		print_r($results);
		
		if(count($results) > 0)
			$customer_id = $results[0]['customer_id'];
		
		if(empty($customer_id))
			die("customer id missing.");
		
//		echo $customer_id;
		
		$data = array(
			'filter_survey_id' => $survey_id,
			'sort'  => $sort,
			'order' => $order,			
		);
		
		$all_questions = array();
		
		$survey_total = $this->model_survey_question->getTotalQuestions($data);
	
		$results = $this->model_survey_question->getQuestions($data);
		
//		print_r($results);		
 
    	foreach ($results as $result) {
    		$answer = array();
    		
    		$question_id = $result['question_id'];
    		
    		$options = array();
    		$question_data = array();
    		
    		$question_info = $result;
      		$question_id = $question_info['question_id'];
      		
      		switch($question_info['qtype']) {
      		case 'text':
      		case 'textarea':
	      		$question_data = array(
	  				'filter_survey_id' => $survey_id,
	  				'filter_question_id' => $question_id,
	  				'filter_check_answer' => 'not-empty',
	  				'filter_customer_id' => $customer_id
	      		);
      			
      			$total_participant = $this->model_survey_survey->getTotalParticipent($question_data);
      			
      			$get_answer = "";
      			if($total_participant) {
      				$get_answer = $this->model_survey_survey->getAnswer($question_data);
      				$get_answer = $get_answer['answer'];
      			}
	      		
	      		$answer[] = array(
					'text' => $get_answer,
					'value' => $total_participant				
				);
      		break;
      		case 'checkbox':
      		case 'radio':
	      		$question_info['lable'] = str_replace("\r","", $question_info['lable']);
	      		$all_lables = explode("\n", $question_info['lable']);
	      		if(!empty($question_info['value'])) {
	      			$question_info['value'] = str_replace("\r","", $question_info['value']);
	      			$all_values = explode("\n", $question_info['value']);
	      		} else {
	      			$all_values = $all_lables;
	      		}      			
	      		
	      		if(!empty($check_answer['answer']))
	      			$default_value = $check_answer['answer'];
	      		else
	      			$default_value = $question_info['default'];
	      		
	      		foreach($all_lables as $key => $each_value) {
	      			      			
	      			$default = 0;
	      			if($default_value == $all_values[$key])
	      				$default = 1;
	      				
	      		    $options[] = array(
		      			'lable' => $all_lables[$key],
		      			'value' => $all_values[$key],
		      			'default' => $default
		      		);	
	      		}
	      		
	      		foreach($options as $each_option) {
	      			
	      			$question_data = array(
	      				'filter_survey_id' => $survey_id,
	      				'filter_question_id' => $question_id,
	      				'filter_customer_id' => $customer_id,      				
	      				'filter_answer' => $each_option['value']
	      			);
	      			
	      			$total_participant = $this->model_survey_survey->getTotalParticipent($question_data);
	
					$answer[] = array(
						'text' => $each_option['lable'],
						'value' => $total_participant,
						'link' => $this->url->link('survey/survey/participents', 'token=' . $this->session->data['token'] . '&survey_id=' . $survey_id . '&question_id=' . $question_id . '&filter_answer=' . $each_option['value'])
					);      			
	      		}
	      		
    			break;
    			case 'default' :
    			case 'lable' :
    			$question_data = array(
	  				'filter_survey_id' => $survey_id,
	  				'filter_question_id' => $question_id,
	  				'filter_check_answer' => 'not-empty',
	  				'filter_customer_id' => $customer_id
	      		);
	      		
    			$answer = array();
    			$answer = $this->model_survey_survey->getAnswer($question_data);
    			break;
    		}
				
			$all_questions[] = array(
				'question_id' => $result['question_id'],
				'title'          => $result['title'],
				'sort_order'     => $result['sort_order'],
				'answer'     => $answer,
				'selected'       => isset($this->request->post['selected']) && in_array($result['question_id'], $this->request->post['selected'])
			);
    	}
    	
//    	print_r($all_questions);
    	
		$output = "";		
		switch($survey_id) {
			case '11': // Personality
				$answer_found = 1;
				
				$all_answers = array();
				foreach($all_questions as $each_question) {
					foreach($each_question['answer'] as $key => $each_answer) {
						if($each_answer['value']) {
							$all_answers[$each_question['sort_order']] = $key;
							$answer_found = 0;
						}								
					}					
				}
				
				$all_weights[1][0] = '2';
				$all_weights[1][1] = '4';
				$all_weights[1][2] = '6';
				
				$all_weights[2][0] = '6';
				$all_weights[2][1] = '4';
				$all_weights[2][2] = '7';
				$all_weights[2][3] = '2';
				$all_weights[2][4] = '1';
				
				$all_weights[3][0] = '4';
				$all_weights[3][1] = '2';
				$all_weights[3][2] = '5';
				$all_weights[3][3] = '7';
				$all_weights[3][4] = '6';
				
				$all_weights[4][0] = '4';
				$all_weights[4][1] = '6';
				$all_weights[4][2] = '2';
				$all_weights[4][3] = '1';
				
				$all_weights[5][0] = '6';
				$all_weights[5][1] = '4';
				$all_weights[5][2] = '3';
				$all_weights[5][3] = '5';
				$all_weights[5][4] = '2';
				
				$all_weights[6][0] = '6';
				$all_weights[6][1] = '4';
				$all_weights[6][2] = '2';
				
				$all_weights[7][0] = '6';
				$all_weights[7][1] = '2';
				$all_weights[7][2] = '4';
				
				$all_weights[8][0] = '6';
				$all_weights[8][1] = '7';
				$all_weights[8][2] = '5';
				$all_weights[8][3] = '4';
				$all_weights[8][4] = '3';
				$all_weights[8][5] = '2';
				$all_weights[8][6] = '1';
				
				$all_weights[9][0] = '7';
				$all_weights[9][1] = '6';
				$all_weights[9][2] = '4';
				$all_weights[9][3] = '2';
				$all_weights[9][4] = '1';
				
				$all_weights[10][0] = '4';
				$all_weights[10][1] = '2';
				$all_weights[10][2] = '3';
				$all_weights[10][3] = '5';
				$all_weights[10][4] = '6';
				$all_weights[10][5] = '1';
				
				$score = 0;
				foreach($all_answers as $key => $each_answer) {
					$score += $all_weights[$key][$each_answer]; 
				}
				
				$all_text = $this->language->get('personality');
				$output .= "Score: ".$score." Points<br /><br />";
				
				foreach($all_text as $each_text) {
					
					if($score <= $each_text['end'] || $each_text['end'] == '+') {
						$output .=	$each_text['text']."<br /><br />";
						break;
					}						
				}
				
				if($answer_found) {
					$output = $this->language->get('text_not_given');
				}
				
//				print_r($all_questions);
//				print_r($all_answers);
//				echo $score;
				
			break;
			case '12': // Myers Briggs Test
				
				$answer_found = 1;
				
				$full_codes[] = array();
				$all_codes[] = array(
					'questions' => array(71,64,57,50,43,36,29,22,15,8,1),
					'codes' => array('E','I'),
					'weight' => '5',
					'total' => '11',
				);
				
				$all_codes[] = array(
					'questions' => array(72,66,65,59,58,52,51,45,44,38,37,31,30,24,23,17,16,10,9,3,2),
					'codes' => array('S','N'),
					'weight' => '10',
					'total' => '21',
				);
				
				$all_codes[] = array(
					'questions' => array(73,68,67,61,60,54,53,47,46,40,39,33,32,26,25,19,18,12,11,5,4),
					'codes' => array('T','F'),
					'weight' => '10',
					'total' => '21',
				);
				
				$all_codes[] = array(
					'questions' => array(74,70,69,63,62,56,55,49,48,42,41,35,34,28,27,21,20,14,13,7,6),
					'codes' => array('J','P'),
					'weight' => '10',
					'total' => '21',
				);
				
				$all_answers = array();				
				foreach($all_questions as $key => $each_question) {					
					foreach($all_codes as $each_code) {
						if(in_array($each_question['sort_order'], $each_code['questions'])) {
							
							if($all_questions[$key]['answer'][0]['value']) { // add wight 1 to each code according to their question grid. 
								if(empty($all_answers[$each_code['codes'][0]]))
									$all_answers[$each_code['codes'][0]] = 1;
								else
									$all_answers[$each_code['codes'][0]] = $all_answers[$each_code['codes'][0]] + 1;
									
							} else if($all_questions[$key]['answer'][1]['value']) {
								if(empty($all_answers[$each_code['codes'][1]]))
									$all_answers[$each_code['codes'][1]] = 1;
								else
									$all_answers[$each_code['codes'][1]] = $all_answers[$each_code['codes'][1]] + 1;
							}
							
							if(0) {
								print_r($each_question);
								print_r($each_code);
								print_r($all_answers);
								die;
							}
						}							
					}
				}
				
				if(count($all_answers) > 1)
					$answer_found = 0;
				
				if(! $answer_found) {				
				$result_code = array();
				foreach($all_codes as $each_code) {
					if($all_answers[$each_code['codes'][0]] > $each_code['weight']) {
						$result_code[$each_code['codes'][0]]['code'] = $each_code['codes'][0];
						$result_code[$each_code['codes'][0]]['score'] = $all_answers[$each_code['codes'][0]];
						$result_code[$each_code['codes'][0]]['percent'] = round((($all_answers[$each_code['codes'][0]] * 100) / $each_code['total']), 2); 
					} else if($all_answers[$each_code['codes'][1]] > $each_code['weight']) {
						$result_code[$each_code['codes'][1]]['code'] = $each_code['codes'][1];
						$result_code[$each_code['codes'][1]]['score'] = $all_answers[$each_code['codes'][1]];
						$result_code[$each_code['codes'][1]]['percent'] = round((($all_answers[$each_code['codes'][1]] * 100) / $each_code['total']), 2);
					}
				}
				
				$result = array();
				$myers_briggs = $this->language->get('myers_briggs');
				$full_code = implode('', array_keys($result_code));
				$result['code'] = $full_code;
				$result['code_result'] = $result_code;
				$result = array_merge($result, $myers_briggs[$full_code]);
				
				ob_start();
				?>
				<table width="100%" border="0" cellpadding="3" cellspacing="3">
					  <tr>
					    <td width="10%"><strong>Code</strong></td>
					    <td width="10%"><strong>Full</strong></td>
					    <td width="10%"><strong>Percent</strong></td>
					    <td width="70%"><strong>Description</strong></td>
					  </tr>
					  <?php foreach($result['code_result'] as $each_code) {?>
					  <tr>
					    <td align="center"><?=$each_code['code'];?></td>
					    <td><?=$myers_briggs[$each_code['code']]['full'];?></td>
					    <td align="center"><?=$each_code['percent'];?></td>
					    <td><?=$myers_briggs[$each_code['code']]['text'];?></td>					    
					  </tr>
					  <? } ?>
					</table><br /><br />
					<table width="100%" border="0" cellpadding="3" cellspacing="3">
					  
					  <tr>
					    <td width="20%" align="right"><strong>Your Code: </strong></td>
					    <td width="80%"><?=$result['code'];?></td>
					  </tr>
					  <tr>
					    <td align="right"><strong>Match Codes: </strong></td>
					    <td><?=implode(', ', $myers_briggs[$result['code']]['matches']);?></td>
					  </tr>
					  <tr>
					    <td align="right"><strong>Symbolic Name: </strong></td>
					    <td><?=$myers_briggs[$result['code']]['name'];?></td>
					  </tr>
					  <tr>
					    <td align="right"><strong>Nature: </strong></td>
					    <td><?=$myers_briggs[$result['code']]['nature'];?></td>
					  </tr>
					  <tr>
					    <td align="right" valign="top"><strong>Summary: </strong></td>
					    <td><?=$myers_briggs[$result['code']]['text'];?></td>
					  </tr>
					</table>
				<?php
				$output = ob_get_clean();
				
				}
				
				if($answer_found) {
					$output = $this->language->get('text_not_given');
				}
				
//				print_r($result);
				
			break;
			case '13': // Shapes Test
				$answer_found = 1;
				$all_shapes = $this->language->get('shapes');
				$all_answers = $all_questions[0]['answer'];
				
//				print_r($all_questions);
				
				foreach($all_answers as $each_answer) {
					$shape_number = preg_replace('/[^0-9]/', '', $each_answer['text']);
					if($each_answer['value']) {
						$output .= $all_shapes[$shape_number]."<br /><br />";
						$answer_found = 0;
					}							
				}
				
				if($answer_found) {
					$output = $this->language->get('text_not_given');
				}
								
			break;
			case '14': // Hierarchy of Needs
				$answer_found = 1;
				$hierarchy_of_needs = $this->language->get('hierarchy_of_needs');
				$all_answers = $all_questions[0]['answer'];
//				print_r($all_answers);
				foreach($all_answers as $each_answer) {
					if($each_answer['value']) {
						$output .= "<strong>".$each_answer['text']."</strong>: ".$hierarchy_of_needs[$each_answer['text']]."<br /><br />";
						$answer_found = 0;
					}							
				}
				
				$output .= $hierarchy_of_needs['help'];
				
				if($answer_found) {
					$output = $this->language->get('text_not_given');
				}				
			break;
			case '15':
				$all_answers = $all_questions[0]['answer'];
//				print_r($all_answers);
				if(!empty($all_answers)) {
					$output .= "Sum: ".$all_answers['answer']." ( 115 )<br /><br /> Time: ".date('i:s', (time() + $all_answers['time_took'] - time())).' (03:00)';
				} else {
					$output = $this->language->get('text_not_given');
				}
			break;
			case '16':
				$score = 0;
				$all_answers = $this->language->get('reasoning');
//				print_r($all_answers);
				foreach($all_questions as $each_question) {
					foreach($each_question['answer'] as $each_answer) {
						
						if($each_answer['value'])
						if($each_answer['text'] == $all_answers[$each_question['sort_order']])
							$score += 1; 
					}
				}
				
				$percent = round(($score * 100 / 25), 2); 
				
				if(!empty($all_answers)) {
					$output .= "Score: ".$score." / 25 ( ".$percent."% )";
				} else {
					$output = $this->language->get('text_not_given');
				}
				
			break;
			default:
				$output = $output = $this->language->get('text_not_configured');
			break;
		}
				
//		echo $output;
//		die;
		
		return $output;
	}
	
	private function validate() {
		if (!$this->user->hasPermission('modify', 'survey/result')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}
		
		if ((strlen(utf8_decode($this->request->post['email'])) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email'])) {
      		$this->error['email'] = $this->language->get('error_email');
    	}    	
    	
		if (! isset($this->request->post['survey_ides']) || count($this->request->post['survey_ides']) < 1) {
      		$this->error['survey_ides'] = $this->language->get('error_survey_ides');
    	}
		
		if (!$this->error) {
			return true;
		} else {
			return false;
		}		
	}
}
?>